# Gamersyde.com by Insayne

import os,sys,time
import urllib,urllib2,re
import xbmcplugin,xbmcgui, xbmcaddon
from GsAPI import common as common

# plugin Constants
__plugin__ = "Gamersyde.com"
__author__ = "Insayne"
__url__ = ""
__svn_url__ = ""
__version__ = "0.5"
__svn_revision__ = "$Revision$"
__XBMC_Revision__ = xbmc.getInfoLabel('System.BuildVersion')
__settings__ = xbmcaddon.Addon(id='plugin.video.gs')

set_lang = int(__settings__.getSetting( "lang" ))
set_ps = int(__settings__.getSetting( "pref_server" ))

#Variables
UAS = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 ( .NET CLR 3.5.30729; .NET4.0C)'

# Generates the main Index
def Generate_Index():
	global set_lang
	if set_lang==0:
		url = 'http://www.gamersyde.com/index_en.html'
	if set_lang==1:
		url = 'http://www.gamersyde.com/index_fr.html'	

	link = common.index_request(url)
	match=re.compile('<div class="news-panel-title">(.+?)<span class="news-posted-by">.+?</div>').findall(link)

	for html in match:
		title = common.get_title(html)
		thumb = 'http://www.gamersyde.com/' + common.get_thumbnail(html)
		link = 'http://www.gamersyde.com/' + common.get_link_to_videopage(html)
		addDir(title,link,1, thumb)
	
	thumb = xbmc.translatePath(os.path.join( os.getcwd(), 'resources', 'images', 'back.png' ))
	link = "1"
	title = "<< Older News (10-20)"
	addDir(title,link,3, thumb)
		
def Generate_Page(pagenum):
	global set_lang
	if int(pagenum) > 0:
	
		page = int(pagenum) * 10
		page = int(page)
		
		page_start = int(page) + 10
		page_end = int(page_start) + 10
		next_page = int(pagenum) + 1
		if set_lang==0:
			url = 'http://www.gamersyde.com/news_ajax_' + str(page) + '_en.html'
		if set_lang==1:
			url = 'http://www.gamersyde.com/news_ajax_' + str(page) + '_fr.html'
		link = common.index_request(url)
		match=re.compile('<div class="news-panel-title">(.+?)<span class="news-posted-by">.+?</div>').findall(link)
		for html in match:
			title = common.get_title(html)
			thumb = 'http://www.gamersyde.com/' + common.get_thumbnail(html)
			link = 'http://www.gamersyde.com/' + common.get_link_to_videopage(html)
			print "DA LINK: " + link
			addDir(title,link,1, thumb)
			
		thumb = xbmc.translatePath(os.path.join( os.getcwd(), 'resources', 'images', 'back.png' ))
		link = "0"
		title = "<< Index"
		addDir(title,link,3, thumb)
	
		thumb = xbmc.translatePath(os.path.join( os.getcwd(), 'resources', 'images', 'back.png' ))
		link = str(next_page)
		title = "<< Older News (" + str(page_start) + "-" + str(page_end) + ")"
		addDir(title,link,3, thumb)


	else:
		Generate_Index()

def Get_Videos(url):
	UAS = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 ( .NET CLR 3.5.30729; .NET4.0C)'
	req = urllib2.Request(url)
	req.add_header('User-Agent', UAS)
	response = urllib2.urlopen(req)
	html=response.read()
	response.close()
	html = html.replace("\n", "")
	html = html.replace("\r", "")

	videos = common.get_video_stream_urls(html)
		
	if len(videos) > 0:
		common.get_video_streams(videos)
		common.get_screenies_from_vids(url,html)
		xbmcplugin.setContent(handle=int(sys.argv[1]), content="movies" )
	else:
		common.get_screenies_from_vids(url,html)

	
# Add Link
def addLink(name,url,iconimage):
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={ "Title": name } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
	return ok

# Add Directory
def addDir(name,url,mode,iconimage):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={ "Title": name } )
	liz.setProperty("Fanart_image", iconimage)
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
	return ok

def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param

params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

if mode==None or url==None or len(url)<1:
	Generate_Index()

# Mode 1:
# This Mode lists the Videos of a Video Item
elif mode==1:
	Get_Videos(url)

	
	
elif mode==2:
	print "MODE 2"
	dl_url = 'http://www.gamersyde.com/' + url
	furl = common.play_video(dl_url)
	
	if furl=="ERROR":
		print "CAN NOT PLAY THIS - NO SOURCE"
	else:
		li=xbmcgui.ListItem(path = furl)
		xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, li)
	
elif mode==3:
	print "MODE 3!"
	Generate_Page(url)
	xbmcplugin.setContent(handle=int(sys.argv[1]), content="movies" )

elif mode==4:
	print "MODE 4"
	print "URL: " + str(url)

	screenshots = common.get_screenshots(url)
	directory = xbmc.translatePath(os.path.join('special://profile/addon_data/plugin.video.gs/', 'cache'))
	common.Generate_Slideshow(screenshots)
	xbmc.executebuiltin("XBMC.SlideShow(" + directory + ")")
	
	

xbmcplugin.endOfDirectory(int(sys.argv[1]))
